/**
 * Tournament
 */

$(document).ready(function(){
});

/**
 * Переменная для хранения протокола матча
 */
var tournamentProtocol = [];

/**
 * Переменная для хранения состава команд
 */
var tournamentProtocolTeams = [];



/**
 * Вывод информационного сообщения
 */
function tournamentAlert(msg){
	alert(msg);
}



/**
 * Обработка ошибки ajax
 */
function tournamentAjaxError(response){
	if (response.error == 'noRight'){
		tournamentAlert(Dictionary.translate('lang_tournament_error_noRight'));
	}else if (response.error == 'noTeams'){
		tournamentAlert(Dictionary.translate('lang_tournament_error_noTeams'));
	}else if (response.error == 'noMember'){
		tournamentAlert(Dictionary.translate('lang_tournament_error_noMember'));
	}else if (response.error == 'noEvenMember'){
		tournamentAlert(Dictionary.translate('lang_tournament_error_noEvenMember'));
	}else if (response.error == 'noProtocolStage'){
		tournamentAlert(Dictionary.translate('lang_tournament_error_noProtocolStage'));
	}else if (response.error == 'noEventTime'){
		tournamentAlert(Dictionary.translate('lang_tournament_error_noEventTime'));
	}else if (response.error == 'noCommentBody'){
		tournamentAlert(Dictionary.translate('lang_tournament_error_noCommentBody'));
	}else{
		tournamentAlert(Dictionary.translate('lang_tournament_error_other')+(response.body?':\r\n'+response.body:''));
	}
}

/**
 * Обраточка успешных ajax-запросов
 */
function tournamentAjaxSuccess(data, action, callback){
	var response = (typeof data == 'undefined' || data.length==0) ? {} : eval( "(" + data + ")" );
	if (response.action == action){
		if (response.status){
			callback(response);
		}else{
			tournamentAjaxError(response);
		}
	}
}

/**
 * Проведение ajax-запросов
 */
function tournamentAjax(area, lang, mode, action, data, callback){
	var res = $.ajax({
		url:'/common/tournament.php?site='+site_id+'&version='+version+'&lang='+lang+'&area='+area+'&mode='+mode+'&action='+action,
		cache: false,
		data: data,
		success:function(data){
			tournamentAjaxSuccess(data, action, callback)
		}
	}); 	
}



/**
 * Проверка корректности поля SHORT_URL
 */
function tournamentCheckShortUrl(area, lang, id, id_name, idResult){
	if (!id_name||!idResult) return false;
	var name = jQuery.trim($('#'+id_name).val());
	if (!name) return false;

	var callback = function(data){
		var response = (typeof data == 'undefined' || data.length==0) ? {} : eval( "(" + data + ")" );
		if (response.action == 'check_short_url'){
			if (response.status){
				$('#'+idResult).val(Dictionary.translate('lang_tournament_check_short_url_ok'));
				//$('#'+idResult).html('<b class="black bg-white">&nbsp;'+Dictionary.translate('lang_tournament_check_short_url_ok')+'&nbsp;<\/b>').removeClass('link-dashed');
			}else{
				$('#'+idResult).val(Dictionary.translate('lang_tournament_check_short_url_fail'));
				//$('#'+idResult).html('<b class="red bg-white">&nbsp;'+Dictionary.translate('lang_tournament_check_short_url_fail')+'&nbsp;<\/b>').removeClass('link-dashed');
				$('#'+id_name).focus();
			}
		}
	}
	
	var res = $.ajax({
		url:'/common/tournament.php?area='+area+'&lang='+lang+'&mode=tournament&action=check_short_url&name='+name+'&id='+id,
		cache: false,
		success:function(data){
			callback(data);
		}
	}); 	
	return false;
}

/**
 * Очистка поля результата проверки поля SHORT_URL
 */
function tournamentClearCheckShortUrlResult(area, idResult){
	$('#'+idResult).val(Dictionary.translate('lang_tournament_check_short_url'));
	//$('#'+idResult).html('&nbsp;'+Dictionary.translate('lang_tournament_check_short_url')+'&nbsp;').addClass('link-dashed');
}



/**
 * Обработчик изменения формы участия
 */
function tournamentRightParticipationChange(area, el){
	$part_select = $('.participation:eq(0) select');
	$part_input = $('.participation:eq(1) input');
	if ( $(el).val() == 1 ) {
		$('.participation').show();
		$part_select.attr('name', '_nonempty_'+$part_select.attr('name'));
		$part_input.attr('name', '_nonempty__number_'+$part_input.attr('name'));
	}else {
		$('.participation').hide();
		$part_select.attr('name', $part_select.attr('name').replace('_nonempty_', ''));
		$part_input.attr('name', $part_input.attr('name').replace('_nonempty__number_', ''));
	}
	return false;
}


/**
 * Открытие формы (попап или что там) для отправки сообщения капитанам команд турнира
 */
function tournamentMsgToTeamsOpen(area, idContainer, idOpenLink){
	//$('#'+idContainer).show();
	$('#'+idOpenLink).click();
}

/**
 * Отправка сообщения капитанам команд турнира
 */
function tournamentMsgToTeams(area, lang, idHideContainer, form){
	var data = {
		id: jQuery.trim(form.elements['tournament_id'+area].value),
		msg: jQuery.trim(form.elements['msg'+area].value)
	}
	var callback = function(response){
		tournamentAlert(Dictionary.translate('lang_tournament_msg_to_teams').replace(':team_count:', response.team_count).replace(':lang_messages:', numeral(response.team_count, Dictionary.translate('lang_tournament_msg_to_teams_lang_messages1'), Dictionary.translate('lang_tournament_msg_to_teams_lang_messages2'), Dictionary.translate('lang_tournament_msg_to_teams_lang_messages3'))));
		//$('#'+idHideContainer).hide();
		$.fancybox.close();
	}
	tournamentAjax(area, lang, 'tournament', 'msg_to_teams', data, callback);
	return false;
}



/**
 * Проверка формы отправки приглашений на турнир
 */
function tournamentCheckFormTeamInvite(form){
	var f = document.forms[form];
	var flag = false;
	var element;
	var form_length = f.elements.length;
	for ( var c=0; c<form_length; c++ ){
		element = f.elements[c];
		if ( element.checked ){
			flag = true;
			break;
		}
	}
	return flag;
}



/**
 * Роспуск турнира
 */
function tournamentCancel(area, lang, id, success_path){
	if ( !confirm(Dictionary.translate('lang_tournament_cancel_confirm')) )
		return false;
	
	var data = {
		id: id
	}
	var callback = function(response){
		tournamentAlert(Dictionary.translate('lang_tournament_cancel'));
		if ( typeof success_path != 'undefined' && success_path.length>0 ){
			document.location.href = success_path;
		}else{
			var reg = /tournament_id=(\d+)/;
			document.location.search = document.location.search.replace(reg, "");
		}
	}
	tournamentAjax(area, lang, 'tournament', 'cancel', data, callback);
	return false;
}



/**
 * Старт турнира
 */
function tournamentStart(area, lang, id, success_path){
	if ( !confirm(Dictionary.translate('lang_tournament_start_confirm')) )
		return false;
	
	var data = {
		id: id
	}
	var callback = function(response){
		tournamentAlert(Dictionary.translate('lang_tournament_start'));
		document.location.href = typeof success_path != 'undefined' && success_path.length>0
			? success_path
			: document.location.href;
	}
	tournamentAjax(area, lang, 'tournament', 'start', data, callback);
	return false;
}



/**
 * Жеребьевку команд турнира
 */
function tournamentToss(area, lang, id, isMix, success_path){
	var data = {
		id: id,
		ismix: isMix
	}
	var callback = function(response){
		tournamentAlert(Dictionary.translate('lang_tournament_start'));
		document.location.href = typeof success_path != 'undefined' && success_path.length>0
			? success_path
			: document.location.href;
	}
	tournamentAjax(area, lang, 'tournament', 'toss', data, callback);
	return false;
}



/**
 * Показ формы добавления объявления к турниру
 */
function tournamentAdForm(area, lang, template, id, idEditContainer, idSeeContainer, idOpenLink){
	var data = {
		id: id,
		template: template,
		idEditContainer: idEditContainer,
		idSeeContainer: idSeeContainer
	}
	var callback = function(response){
		$('#'+idEditContainer).html(response.body);
		//$('#'+idEditContainer).show();
		$('#'+idOpenLink).click();
	}
	tournamentAjax(area, lang, 'tournament', 'ad_form', data, callback);
	return false;
}

/**
 * Добавление объявления к турниру
 */
function tournamentAdUpdate(area, lang, template, idHideContainer, idContainer, form){
	var data = {
		id: jQuery.trim(form.elements['tournament_id'+area].value),
		template: template,
		title: jQuery.trim(form.elements['TITLE'+area].value),
		body: jQuery.trim(form.elements['BODY'+area].value)
	}
	var callback = function(response){
		//$('#'+idHideContainer).hide();
		$.fancybox.close();
		$('#'+idContainer+' .empty').hide();
		$('#'+idContainer).html(response.body+$('#'+idContainer).html());
	}
	tournamentAjax(area, lang, 'tournament', 'ad_update', data, callback);
	return false;
}

/**
 * Удаление объявления
 */
function tournamentAdDelete(area, lang, template, id, idAd){
	if ( !confirm(Dictionary.translate('lang_tournament_ad_delete_confirm')) )
		return false;

	var data = {
		id: id,
		id_ad: idAd
	}
	var callback = function(response){
		$('.class_ad_'+id+'_'+idAd+'').hide();
	}
	tournamentAjax(area, lang, 'tournament', 'ad_delete', data, callback);
	return false;
}



/**
 * Одобрение запроса на участие в турнире
 */
function tournamentMemberApprove(area, lang, id, team_id, container, containerHide){
	if ( !confirm(Dictionary.translate('lang_tournament_org_approve_confirm')) )
		return false;

	var data = {
		id: id,
		team_id: team_id
	}
	var callback = function(response){
		$('#'+container).text(Dictionary.translate('lang_tournament_approve'));
		$('#'+containerHide).empty();
		if ( response.isRightTournamentStart ){
			$('#id_TournamentStartButton')
				.each(function(){this.onclick = function(){return false;}})
				.unbind('click')
				.bind('click', function(){return tournamentOnClickStartButton();})
				.attr('disabled', '');
		}
		$('#id_TournamentMessageButton')
			.each(function(){this.onclick = function(){return false;}})
			.unbind('click')
			.bind('click', function(){return tournamentOnClickMessageButton();})
			.attr('disabled', '');
		$('#id_TournamentCancelButton')
			.each(function(){this.onclick = function(){return false;}})
			.unbind('click')
			.bind('click', function(){return tournamentOnClickCancelButton();})
			.attr('disabled', '');
	}
	tournamentAjax(area, lang, 'member', 'approve', data, callback);
	return false;
}

/**
 * Отказ в участии в турнире
 */
function tournamentMemberDenied(area, lang, id, team_id, container, containerHide){
	if ( !confirm(Dictionary.translate('lang_tournament_org_denied_confirm')) ) 
		return false;

	var data = {
		id: id,
		team_id: team_id
	}
	var callback = function(response){
		$('#'+container).text(Dictionary.translate('lang_tournament_denied'));
		$('#'+containerHide).empty();
	}
	tournamentAjax(area, lang, 'member', 'denied', data, callback);
	return false;
}

/**
 * Отправка запроса на участие в турнире (со стороны капитана команды)
 */
function tournamentMemberTeamRequest(area, lang, id, containersRemove){
	var data = {
		id: id
	}
	var callback = function(response){
		for ( var i=0; i<containersRemove.length; i++ )
			$('#'+containersRemove[i]).remove();
		tournamentGlobalRefreshButtonLine(area, lang);
		tournamentAlert(Dictionary.translate('lang_tournament_team_request'));
	}
	tournamentAjax(area, lang, 'member', 'team_request', data, callback);
	return false;
}

/**
 * Одобрение участия в турнире (со стороны капитана команды)
 */
function tournamentMemberTeamApprove(area, lang, id, containersRemove){
	if ( !confirm(Dictionary.translate('lang_tournament_team_approve_confirm')) )
		return false;

	var data = {
		id: id
	}
	var callback = function(response){
		for ( var i=0; i<containersRemove.length; i++ )
			$('#'+containersRemove[i]).remove();
		tournamentGlobalRefreshButtonLine(area, lang);
	}
	tournamentAjax(area, lang, 'member', 'team_approve', data, callback);
	return false;
}

/**
 * Отказ от участия в турнире (со стороны капитана команды)
 */
function tournamentMemberTeamDenied(area, lang, id, containersRemove, containersShow){
	if ( !confirm(Dictionary.translate('lang_tournament_team_denied_confirm')) )
		return false;

	var data = {
		id: id
	}
	var callback = function(response){
		for ( var i=0; i<containersRemove.length; i++ )
			$('#'+containersRemove[i]).remove();
		for ( var i=0; i<containersShow.length; i++ )
			$('#'+containersShow[i]).show();
		tournamentGlobalRefreshButtonLine(area, lang);
	}
	tournamentAjax(area, lang, 'member', 'team_denied', data, callback);
	return false;
}



/**
 * Показ формы изменения параметров матча на странице календаря
 */
function tournamentCalendarMatchForm(area, lang, template, id, idEditContainer, idSeeContainer){
	var data = {
		id: id,
		template: template,
		idEditContainer: idEditContainer,
		idSeeContainer: idSeeContainer
	}
	var callback = function(response){
		$('#'+idEditContainer).html(response.body);
		$('#'+idSeeContainer).hide();
		$('#'+idEditContainer).show();
	}
	tournamentAjax(area, lang, 'tournament', 'match_form', data, callback);
	return false;
}

/**
 * Изменение параметров матча на странице календаря
 */
function tournamentCalendarMatchUpdate(area, lang, template, idEditContainer, idSeeContainer, form){
	var data = {
		id: jQuery.trim(form.elements['tournament_match_id'+area].value),
		date_play: jQuery.trim(form.elements['DATE_PLAY'+area].value),
		time_play: jQuery.trim(form.elements['TIME_PLAY'+area].value),
		additional: jQuery.trim(form.elements['ADDITIONAL'+area].value),
		is_calendar: 1
	}
	var callback = function(response){
		tournamentCalendarMatchBlock(area, lang, data.id, template, idSeeContainer, idEditContainer);
	}
	tournamentAjax(area, lang, 'tournament', 'match_update', data, callback);
	return false;
}

/**
 * Отображение блока параметров матча на странице календаря
 */
function tournamentCalendarMatchBlock(area, lang, id, template, idSeeContainer, idEditContainer){
	var data = {
		id: id,
		template: template
	}
	var callback = function(response){
		$('#'+idSeeContainer).html(response.body);
		$('#'+idEditContainer).hide();
		$('#'+idSeeContainer).show();
		$('#'+idEditContainer).html('');
	}
	tournamentAjax(area, lang, 'tournament', 'match_block', data, callback);
	return false;
}



/**
 * Показ формы изменения параметров матча
 */
function tournamentMatchInfoForm(area, lang, template, id, idEditContainer){
	var data = {
		id: id,
		template: template,
		idEditContainer: idEditContainer
	}
	var callback = function(response){
		$('#'+idEditContainer).html(response.body);
	}
	tournamentAjax(area, lang, 'match', 'info_form', data, callback);
	return false;
}

/**
 * Изменение параметров матча
 */
function tournamentMatchInfoUpdate(area, lang, template, form){
	var data = {
		id: jQuery.trim(form.elements['tournament_match_id'+area].value),
		date_play: jQuery.trim(form.elements['DATE_PLAY'+area].value),
		time_play: jQuery.trim(form.elements['TIME_PLAY'+area].value),
		weather: jQuery.trim(form.elements['WEATHER'+area].value),
		additional: jQuery.trim(form.elements['ADDITIONAL'+area].value),
		team1_goal: jQuery.trim(form.elements['TEAM1_GOAL'+area].value),
		team2_goal: jQuery.trim(form.elements['TEAM2_GOAL'+area].value)
	}
	var callback = function(response){
		tournamentMatchInfoBlock(area, lang, data.id, template);
	}
	tournamentAjax(area, lang, 'match', 'info_update', data, callback);
	return false;
}

/**
 * Отмена операции
 */
function tournamentMatchInfoCancel(area, lang, id, template){
	tournamentMatchInfoBlock(area, lang, id, template);
	return false;
}

/**
 * Отображение блока параметров матча
 */
function tournamentMatchInfoBlock(area, lang, id, template){
	var data = {
		id: id,
		template: template
	}
	var callback = function(response){
		$('#id_MatchInfo'+area).html(response.body);
		$('#id_MatchResult'+area).html(response.score);
	}
	tournamentAjax(area, lang, 'match', 'info_block', data, callback);
	return false;
}



/**
 * Показ формы заполнения состава команд матча
 */
function tournamentMatchPlayersForm(area, lang, template, id, idEditContainer, team_number){
	var data = {
		id: id,
		template: template,
		team_number: team_number,
		idEditContainer: idEditContainer
	}
	var callback = function(response){
		$('#'+idEditContainer).html(response.body);
	}
	tournamentAjax(area, lang, 'match', 'players_form', data, callback);
	return false;
}

/**
 * Изменение состава команд на матч
 */
function tournamentMatchPlayersUpdate(area, lang, template, form, team_number){
	var players = [];
	$(form).find('input[name^="PLAYERS'+area+'"]').each(function(index,element){
		if ( element.checked == 1 ){
			re = "^PLAYERS"+area+"\\[(\\d+)\\]$";
			found = element.name.match(re);
			if ( typeof found != 'undefined' ){
				players.push({'player':found[1]});
			}
		}
	});
	
	if ( !players.length ){
		tournamentAlert(Dictionary.translate('lang_tournament_error_noPlayersSelected'));
		return false;
	}

	var data = {
		id: jQuery.trim(form.elements['tournament_match_id'+area].value),
		team_id: jQuery.trim(form.elements['team_id'+area].value),
		players: jQuery.toJSON(players)
	}
	var callback = function(response){
		tournamentMatchPlayersBlock(area, lang, data.id, template, team_number);
	}
	tournamentAjax(area, lang, 'match', 'players_update', data, callback);
	return false;
}

/**
 * Отмена операции
 */
function tournamentMatchPlayersCancel(area, lang, id, template, team_number){
	tournamentMatchPlayersBlock(area, lang, id, template, team_number);
	return false;
}

/**
 * Отображение блока состава команд матча
 */
function tournamentMatchPlayersBlock(area, lang, id, template, team_number){
	var data = {
		id: id,
		team_number: team_number,
		template: template
	}
	var callback = function(response){
		$('#id_Team'+team_number+'Players'+area).html(response.body);
	}
	tournamentAjax(area, lang, 'match', 'players_block', data, callback);
	return false;
}



/**
 * Показ формы заполнения протокола матча
 */
function tournamentMatchProtocolForm(area, lang, template, id, protocol_id, idEditContainer, idSeeContainer, idOpenLink){
	var data = {
		id: id,
		protocol_id: protocol_id,
		template: template,
		idEditContainer: idEditContainer,
		idSeeContainer: idSeeContainer
	}
	var callback = function(response){
		$('#'+idEditContainer).html(response.body);
		//$('#'+idEditContainer).show();
		$('#'+idOpenLink).click();
	}
	tournamentAjax(area, lang, 'match', 'protocol_form', data, callback);
	return false;
}

/**
 * Изменение протокола матча
 */
function tournamentMatchProtocolUpdate(area, lang, template, idHideContainer, form){
	var data = {
		id: jQuery.trim(form.elements['tournament_match_id'+area].value),
		protocol_id: jQuery.trim(form.elements['tournament_protocol_id'+area].value),
		template: template,
		event_time: jQuery.trim(form.elements['EVENT_TIME'+area].value),
		protocol_type_id: jQuery.trim(form.elements['PROTOCOL_TYPE_ID'+area].value),
		is_head_scored: (form.elements['IS_HEAD_SCORED'+area].checked?1:0),
		is_penalty_scored: (form.elements['IS_PENALTY_SCORED'+area].checked?1:0),
		is_own_goal: (form.elements['IS_OWN_GOAL'+area].checked?1:0),
		team_id: jQuery.trim(form.elements['TEAM_ID'+area].value),
		footballer_id: jQuery.trim(form.elements['FOOTBALLER_ID'+area].value),
		assistant_id: jQuery.trim(form.elements['ASSISTANT_ID'+area].value),
		body: jQuery.trim(form.elements['BODY'+area].value)
	}
	var callback = function(response){
		//$('#'+idHideContainer).hide();
		$.fancybox.close();
		var protocol = response.protocol;
		// удалить старую запись (с таким же ID)
		var protocol_length = tournamentProtocol[area].length;
		if ( protocol_length>0 ){
			var tmpTournamentProtocol = [];
			for ( var i=0; i<protocol_length; i++ ){
				if ( tournamentProtocol[area][i].ID != protocol.TOURNAMENT_PROTOCOL_ID ){
					tmpTournamentProtocol.push(tournamentProtocol[area][i]);
				}
			}
			tournamentProtocol[area] = tmpTournamentProtocol;
		}
		// добавить новую
		tournamentProtocol[area].push({'ID':protocol.TOURNAMENT_PROTOCOL_ID,'MATCH_ID':protocol.TOURNAMENT_MATCH_ID,'EVENT_TIME':protocol.EVENT_TIME,'BLOCK':protocol.BLOCK});
		tournamentRefreshProtocol(area, lang, 1);
		tournamentMatchPlayersBlock(area, lang, data.id, template, 1);
		tournamentMatchPlayersBlock(area, lang, data.id, template, 2);
	}
	tournamentAjax(area, lang, 'match', 'protocol_update', data, callback);
	return false;
}

/**
 * Удаление записи протокола матча
 */
function tournamentProtocolDelete(area, lang, template, id, idProtocol){
	if ( !confirm(Dictionary.translate('lang_tournament_match_protocol_update_confirm')) )
		return false;

	var data = {
		id: id,
		id_protocol: idProtocol
	}
	var callback = function(response){
		tmpPROTOCOL = [];
		for ( var i=0; i<tournamentProtocol[area].length; i++ ){
			if ( !(tournamentProtocol[area][i].MATCH_ID == id && tournamentProtocol[area][i].ID == idProtocol) ){
				tmpPROTOCOL.push(tournamentProtocol[area][i]);
			}
		}
		tournamentProtocol[area] = tmpPROTOCOL;
		tournamentRefreshProtocol(area, lang, 1);
		tournamentMatchPlayersBlock(area, lang, id, template, 1);
		tournamentMatchPlayersBlock(area, lang, id, template, 2);
	}
	tournamentAjax(area, lang, 'match', 'protocol_delete', data, callback);
	return false;
}

/**
 * Отображение протокола матча на странице
 */
function tournamentRefreshProtocol(area, lang, withRight){
	var out = '';
	var protocol_length = tournamentProtocol[area].length;

	if ( protocol_length>0 ){
		tournamentProtocol[area].sort( function(a,b){return a.EVENT_TIME==b.EVENT_TIME ? (a.ID>b.ID)-(a.ID<b.ID) : (a.EVENT_TIME>b.EVENT_TIME)-(a.EVENT_TIME<b.EVENT_TIME)} );
		for ( var i=0; i<protocol_length; i++ )
		{
			out += tournamentProtocol[area][i].BLOCK.replace('<\/script>', '</script>');
		}
	}
	$('#id_PROTOCOL'+area).html(out.length ? out : Dictionary.translate('lang_tournament_match_protocol_empty'));
	if ( withRight ){
		$('.editPossibility').show();
	}
	return false;
}

/**
 * Обработчик изменения типа события в форме протокола матча
 */
function tournamentMatchProtocolTypeChange(area, protocol_id, form){
	var val = $('form[name='+$(form).attr("name")+'] select[name=PROTOCOL_TYPE_ID'+area+']').val();
	$('.class1,.class2,.class3,.class4,.class5,.class6,.class7,.class8').hide();
	$('.class'+val).show();
	tournamentMatchProtocolTeamChange(area, protocol_id, form);
  
  var team = $('select#TEAM_ID'+ area, $(form));
  var footballer = $('select#FOOTBALLER_ID'+ area, $(form));
  var assistant = $('select#ASSISTANT_ID'+ area, $(form));
  if (val == '') {
    changePrefixInName(team, '_nonempty_', 'remove');
    changePrefixInName(footballer, '_nonempty_', 'remove');
  }
  else {
    changePrefixInName(team, '_nonempty_', 'add');
    changePrefixInName(footballer, '_nonempty_', 'add');
  }
  if (val == '2') {
    changePrefixInName(assistant, '_nonempty_', 'add');
  }
  else {
    changePrefixInName(assistant, '_nonempty_', 'remove');
  }
  
	return false;
}


/**
 * Обработчик изменения команды в форме протокола матча
 */
function tournamentMatchProtocolTeamChange(area, protocol_id, form){
	var val = $('form[name='+$(form).attr("name")+'] select[name=TEAM_ID'+area+']').val();
	protocol_id = protocol_id > 0 ? protocol_id : 0;
	if ( typeof tournamentProtocolTeams[area][protocol_id][val] == 'undefined' ) return false;
	var players = tournamentProtocolTeams[area][protocol_id][val].PLAYERS;
	var type_replacement = $('form[name='+$(form).attr("name")+'] select[name=PROTOCOL_TYPE_ID'+area+']').val() == 2 ? true : false; 
	$('form[name='+$(form).attr("name")+'] select[name=FOOTBALLER_ID'+area+']').empty().append($('<option></option>').attr('value', '').text(''));
	$('form[name='+$(form).attr("name")+'] select[name=ASSISTANT_ID'+area+']').empty().append($('<option></option>').attr('value', '').text(''));
	for ( var i=0; i<players.length; i++ ){
		if ( !players[i].SELECTED && !players[i].REPLACEMENT && !type_replacement) continue;
		$('form[name='+$(form).attr("name")+'] select[name=ASSISTANT_ID'+area+']').append($('<option></option>').attr('value', players[i].ID).attr('selected', players[i].ASSISTANT_SELECTED?'selected':'').text(players[i].NICK));
		if ( !players[i].SELECTED && !players[i].REPLACEMENT ) continue;
		$('form[name='+$(form).attr("name")+'] select[name=FOOTBALLER_ID'+area+']').append($('<option></option>').attr('value', players[i].ID).attr('selected', players[i].FOOTBALLER_SELECTED?'selected':'').text(players[i].NICK));
	}
	return false;
}



/**
 * Показ формы добавления комментария к матчу
 */
function tournamentMatchCommentsForm(area, lang, template, id, idEditContainer, idSeeContainer, idOpenLink){
	var data = {
		id: id,
		template: template,
		idEditContainer: idEditContainer,
		idSeeContainer: idSeeContainer
	}
	var callback = function(response){
		$('#'+idEditContainer).html(response.body);
		//$('#'+idEditContainer).show();
		$('#'+idOpenLink).click();
	}
	tournamentAjax(area, lang, 'match', 'comments_form', data, callback);
	return false;
}

/**
 * Добавление комментария к матчу
 */
function tournamentMatchCommentsUpdate(area, lang, template, idHideContainer, idContainer, form){
	var data = {
		id: jQuery.trim(form.elements['tournament_match_id'+area].value),
		template: template,
		body: jQuery.trim(form.elements['BODY'+area].value)
	}
	var callback = function(response){
		//$('#'+idHideContainer).hide();
		$.fancybox.close();
		$('#'+idContainer+' .empty').hide();
		$('#'+idContainer).html(response.body+$('#'+idContainer).html());
	}
	tournamentAjax(area, lang, 'match', 'comments_update', data, callback);
	return false;
}



/**
 * Обработка нажатия кнопки "К редактированию" в строке управляющего меню
 */
function tournamentGlobalToEdit(area, lang, mode){
	if ( mode == 'tournament_about' ){
		$('#idGlobalToEditButton'+area).hide();
		$('#idGlobalToSeeButton'+area).show();
		$('#id_SEE'+area).hide();
		$('#id_EDIT'+area).show();
	}
	if ( mode == 'tournament_rights' ){
		$('#idGlobalToEditButton'+area).hide();
		$('#idGlobalToSeeButton'+area).show();
		$('#id_SEE'+area).hide();
		$('#id_EDIT'+area).show();
	}
	if ( mode == 'match_card' ){
		$('#idGlobalToEditButton'+area).hide();
		$('#idGlobalToSeeButton'+area).show();
		$('.editPossibility').show();
	}
	tournamentGlobalRefreshButtonLine(area, lang);
	return false;
}

/**
 * Обработка нажатия кнопки "К просмотру" в строке управляющего меню
 */
function tournamentGlobalToSee(area, lang, mode){
	if ( mode == 'tournament_about' ){
		$('#idGlobalToSeeButton'+area).hide();
		$('#idGlobalToEditButton'+area).show();
		$('#id_EDIT'+area).hide();
		$('#id_SEE'+area).show();
	}
	if ( mode == 'tournament_rights' ){
		$('#idGlobalToSeeButton'+area).hide();
		$('#idGlobalToEditButton'+area).show();
		$('#id_EDIT'+area).hide();
		$('#id_SEE'+area).show();
	}
	if ( mode == 'match_card' ){
		tournamentMatchCardToSee();
		$('#idGlobalToSeeButton'+area).hide();
		$('#idGlobalToEditButton'+area).show();
		$('.editPossibility').hide();
	}
	tournamentGlobalRefreshButtonLine(area, lang);
	return false;
}

/**
 * Обновление полоски с кнопками
 */
function tournamentGlobalRefreshButtonLine(area, lang){
	var html = jQuery.trim($('.trn_title_toolbar .ss').html());
	if ( html.length < 1 ){
		$('.trn_title_toolbar').hide();
	}
	return false;
}


/**
 * Добавление или удаление префикса к атрибуту name элемента
 */
function changePrefixInName(element, prefix, type) {
  var attribute = 'name';
  if ((type == 'add' || type == 'remove') && typeof prefix !== 'undefined' && prefix.length > 0) {
    var name = $(element).attr(attribute).replace(new RegExp(prefix, 'g'), '');
    if (type == 'add') {
      $(element).attr(attribute, prefix + name);
    }
    else if (type == 'remove') {
      $(element).attr(attribute, name);
    }
    return true;
  }
  return false;
}
